package com.lanhao.aot.spider.service;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.script.Invocable;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;

import cn.hutool.http.HttpRequest;

//@Service
public class NetSpiderFor17TrackService {
	private static Logger logger = LoggerFactory.getLogger(NetSpiderFor17TrackService.class);
	public static final String trackUrl = "https://t.17track.net/restapi/track";

//	@Resource
	private Invocable invocable;

	public String track(HttpServletRequest request, String trackNum) {
		try {
			String data = "{\"guid\":\"\",\"data\":[{\"num\":\"" + trackNum + "\"}],\"timeZoneOffset\":-480}";
			String lastEventId = (String) invocable.invokeFunction("get_cookie", data);
			logger.info("lastEventId={}", lastEventId);
			request.getCookies();

			Map<String, Object> paramMap = new HashMap<>();
			paramMap.put("data", data);
			String trackResult = HttpRequest.post(trackUrl)
//					.header(Header.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36") // 头信息，多个头信息多次调用此方法即可
					.header("cookie", "Last-Event-ID=" + lastEventId).form(paramMap) // 表单内容
//					.body(data)
					.timeout(20000)// 超时，毫秒
					.execute().body();
			logger.info("trackResult=" + trackResult);
			return trackResult;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return StringUtils.EMPTY;
	}
}